#include "pcappacket.h"
#include <QDebug>

CPCapPktData::CPCapPktData(QObject *parent) :
    QObject(parent)
{
    qDebug("[CPCapPktData]constructed");
}

CPCapPktData::~CPCapPktData()
{
    qDebug("[CPCapPktData]destroyed");
}

const QByteArray &CPCapPktData::data() const
{
    return m_bytes;
}

void CPCapPktData::setData(const QString &data)
{
    m_bytes.clear();
    m_bytes.append(data);
}

CPCapPacket::CPCapPacket(QObject *parent) :
    QObject(parent)
{
    qDebug("[CPCapPacket]constructed");
}

CPCapPacket::~CPCapPacket()
{
    qDebug("[CPCapPacket]destroyed");
}

QQmlListProperty<QObject> CPCapPacket::data()
{
    return QQmlListProperty<QObject>(this, m_data);
}

int CPCapPacket::headerLength()
{
    return 0;
}

int CPCapPacket::payloadLength()
{
    int length = 0;
    for (auto last = m_data.begin(); last != m_data.end(); ++last) {
        CPCapPacket *p1 = dynamic_cast<CPCapPacket*>(*last);
        if (Q_NULLPTR != p1) {
            length += p1->headerLength();
            length += p1->payloadLength();
        } else {
            CPCapPktData *p2 = dynamic_cast<CPCapPktData*>(*last);
            if (Q_NULLPTR != p2) {
                length += p2->data().length();
            }
        }
    }
    return 0;
}

bool CPCapPacket::buildHeader(QByteArray &data)
{
    Q_UNUSED(data);
    qDebug() << "Packet: build header";
    return true;
}

bool CPCapPacket::buildPacket(QByteArray &data)
{
    if (!buildHeader(data)) {
        return false;
    }

    for (auto last = m_data.begin(); last != m_data.end(); ++last) {
        CPCapPacket *p1 = dynamic_cast<CPCapPacket*>(*last);
        if (Q_NULLPTR != p1) {
            if (!p1->buildPacket(data)) {
                return false;
            }
        } else {
            CPCapPktData *p2 = dynamic_cast<CPCapPktData*>(*last);
            if (Q_NULLPTR != p2) {
                data.append(p2->data());
            }
        }
    }
    return true;
}
